<template>
    <div class="cart" @click="couponAvailable = false" style="height: 100%;">
        <BaseHeader></BaseHeader>
        <!-- LOGO 搜索 -->
        <div class="width_1200 logo" style="margin-top: 70px;
         display: flex; justify-content: center;font-size: 20px;
         font-weight: 700;">
            <div>
                <!-- <router-link to="/"><img :src="$store.state.logoImg" /></router-link> -->
                <div>
                    选品库(<span>{{ goodsTotal }}</span>)
                </div>
            </div>
            <!-- <Search v-if="false" :showTag="false" :showLogo="false"></Search> -->
        </div>
        <Divider />
        <!-- 选品库主体 -->
        <div class="cart-content width_1200 center" :style="  { minHeight: `${cartHeadth}px`}">
            <div class="available-area" v-if="false">
                <div class="cart-steps">
                    <span :class="stepIndex == 0 ? 'active' : ''">1.我的选品库</span>
                    <Icon :class="stepIndex == 0 ? 'active-arrow' : ''" custom="icomoon icon-next"></Icon>
                    <span :class="stepIndex == 1 ? 'active' : ''">2.填写订单信息</span>
                    <Icon :class="stepIndex == 1 ? 'active-arrow' : ''" custom="icomoon icon-next"></Icon>
                    <span :class="stepIndex == 2 ? 'active' : ''">3.成功提交订单</span>
                </div>
            </div>
            <!-- 选品库商品列表 -->
            <div class="cart-goods">
                <div class="cart-goods-title">
                    <div class="width_150">
                        <Checkbox v-model="allChecked" @on-change="changeChecked(allChecked, 'all')">全选</Checkbox>
                    </div>
                    <div class="goods-title">商品</div>
                    <div class="width_150">单价（元）</div>
                    <div class="width_100">数量</div>
                    <div class="width_150">小计</div>
                    <div class="width_100">操作</div>
                </div>
                <div v-if="skuList.length === 0" class="cart-empty">
                    <p>选品库空空如也</p>
                    <router-link to="/">去选购&gt;</router-link>
                </div>

                <div v-else class="cart-goods-items">
                    <template v-for="(goods, goodsIndex) in skuList">
                        <div class="goods-item">
                            <!-- //:key="goodsIndex" -->
                            <div class="width_150" style="width: 150px;">
                                <Checkbox v-model="goods.checked"
                                    @on-change="changeChecked(goods.checked, 'goods', goods.goods_id, goodsIndex)">
                                </Checkbox>
                            </div>
                            <div class="goods-title" @click="goGoodsDetail(goods.goods_id)">
                                <img :src="goods.goods.photo || '../assets/images/goodsDetail/item-detail-1.jpg'" />
                                <div style="display: flex; flex-direction: column; justify-content: space-between;">
                                    <p>
                                        {{ goods.goodssku.goods_name }}
                                    </p>

                                    <p>
                                        <Tag class="goods-show-tag" color="red">{{ goods.goodsorign }}</Tag>
                                        <Tag class="goods-show-tag" color="blue">{{ goods.cangku }}</Tag>
                                    </p>
                                    <!-- 
                                    <p v-if="false">
                                        <Tag v-if="goods.salesModel === 'WHOLESALE'" class="goods-show-tag" color="purple">
                                            批发商品
                                        </Tag>
                                    </p>
                                    <template v-for="(promotion, promotionIndex) in goods.promotions" v-if="false">
                                        <div class="promotion" :key="promotionIndex" v-if="promotion.promotionType === 'SECKILL'">
                                            <span>秒杀</span>
                                            <promotion :time="promotion.endTime" type="cart"></promotion>
                                        </div>
                                    </template>
<template v-for="(promotion, promotionIndex) in goods.promotions" v-if="false">
                                        <div class="promotion" :key="promotionIndex" v-if="promotion.promotionType === 'FULL_DISCOUNT'">
                                            <span>满优惠活动</span>
                                            <promotion :time="promotion.endTime" type="cart"></promotion>
                                        </div>
                                    </template> -->
                                </div>
                            </div>
                            <div class="width_150">
                                {{ goods.goodssku.fx_price | unitPrice("￥") }}
                            </div>
                            <div class="width_100">
                                <InputNumber :min="1" size="small" v-model="goods.cartnum"
                                    @on-change="changeNum(goods.cartnum, goods.goods_id, goodsIndex)"></InputNumber>
                                <div class="fontsize_12" v-if="false">
                                    {{ goods.goodssku.stock > 0 ? "有货" : "无货" }}
                                </div>
                            </div>
                            <div class="width_150">
                                {{ goodsTotalPrice(goods) | unitPrice("￥") }}
                            </div>
                            <div class="width_100">
                                <Button v-if="!goods.errorMessage" size="small" type="primary"
                                    @click="delGoods(goods.goods_id)">删除</Button>
                                <Button v-if="!goods.errorMessage && false" size="small" type="info"
                                    @click="collectGoods(goods.goods_id)" style="margin-left: 10px">收藏</Button>
                            </div>
                            <div class="error-goods" v-if="goods.errorMessage">
                                <div style="margin-top: 20px">{{ goods.errorMessage }}</div>
                                <Button type="primary" @click="delGoods(goods.id)">删除</Button>
                            </div>
                        </div>
                    </template>
                </div>

                <!-- 底部支付栏 -->
                <div class="cart-goods-footer">
                    <div>
                        <div class="width_60">
                            <Checkbox v-model="allChecked" @on-change="changeChecked(allChecked, 'all')">全选</Checkbox>
                        </div>
                        <div class="width_100 handle-btn" @click="delGoods()">
                            删除选中商品
                        </div>
                        <!-- <div class="width_100 handle-btn" @click="collectGoods">移到我的收藏</div> -->
                        <div class="width_100 handle-btn" @click="clearCart">
                            清空选品库
                        </div>
                    </div>
                    <div>
                        <div class="selected-count">
                            已选择<span>{{ checkedNum }}</span>件商品
                        </div>
                        <div class="pay ml_20" @click="pay" v-if="purchase && purchase.type || true">提交</div>
                        <!-- ----------------------------提交按钮 -->
                    </div>
                    
                </div>
            </div>
            <Spin size="large" fix v-if="loading"></Spin>
        </div>
        <Safedata></Safedata>
        <!-- <BaseFooter></BaseFooter> -->
    </div>
</template>

<script>
import Promotion from "@/components/goodsDetail/Promotion";
import Search from "@/components/Search";
import * as APICart from "@/api/cart";
import * as APIMember from "@/api/member";

import { deepClone } from "@/plugins/Foundation";
import Storage from "@/plugins/storage";

import { Input } from 'view-design';

export default {
    name: "Cart",
    beforeRouteEnter(to, from, next) {
        window.scrollTo(0, 0);
        next();
    },
    components: {
        Search,
        Promotion,
    },
    data() {
        return {
            couponAvailable: false, // 展示优惠券
            stepIndex: 0, // 当前处于哪一步，选品库==0，填写订单信息==1，成功提交订单==2
            goodsTotal: 0, // 商品数量
            checkedNum: 0, // 选中数量
            allChecked: false, // 全选
            loading: false, // 加载状态
            cartList: [], // 选品库列表
            couponList: [], // 优惠券列表
            priceDetailDTO: {}, // 价格明细
            skuList: [], // sku列表,
            userInfo: {},
            purchase: { type: '', id: '' },
            purchaseVal: '',
            cartHeadth:''
        };
    },

    created() {
        if (Storage.getItem('userInfo') && Storage.getItem('userInfo') != 'undefined') {
            this.userInfo = JSON.parse(Storage.getItem('userInfo'));
        }

        if (Storage.getItem('PURCHASE') && Storage.getItem('PURCHASE') != 'undefined') {
            this.purchase = JSON.parse(Storage.getItem('PURCHASE'));
        }
    },

    computed: {
        // 单件商品总金额
        goodsTotalPrice() {
            return function (goods) {
                return (goods.goodssku.fx_price * goods.num).toFixed(2);
            }
        }
    },

    methods: {
        // 跳转商品详情
        goGoodsDetail(goodsId) {
            /* let routeUrl = this.$router.resolve({
                path: "/goodsDetail",
                query: {
                    skuId,
                    goodsId
                },
            });
            window.open(routeUrl.href, "_blank"); */
            this.$router.push({
                path: '/goodsDetail',
                query: {
                    goods_id: goodsId
                }
            })
        },
        // 跳转店铺首页
        goShopPage(id) {
            let routeUrl = this.$router.resolve({
                path: "/Merchant",
                query: {
                    id
                },
            });
            window.open(routeUrl.href, "_blank");
        },
        // 收藏商品
        collectGoods(id) {
            this.$Modal.confirm({
                title: "收藏",
                content: "<p>商品收藏后可在个人中心我的收藏查看</p>",
                onOk: () => {
                    APIMember.collectGoods("GOODS", id).then((res) => {
                        if (res.success) {
                            this.$Message.success("收藏商品成功");
                            this.getCartList();
                        }
                    });
                },
                onCancel: () => { },
            });
        },
        // 删除商品
        delGoods(id) {
            const idArr = [];
            if (!id) {
                this.skuList.forEach((goods) => {
                    if (goods.checked) {
                        idArr.push(goods.goods_id);
                    }
                });
            } else {
                idArr.push(id);
            }
            this.$Modal.confirm({
                title: "删除",
                content: "<p>确定要删除该商品吗？</p>",
                onOk: () => {
                    APICart.delCartGoods({
                        goods_id: idArr.toString()
                    }).then((res) => {
                        if (res.code == 1) {
                            this.$Message.success("删除成功");
                            this.getCartList();
                        } else {
                            this.$Message.error(res.msg);
                        }
                    });
                },
            });
        },
        // 清空选品库
        clearCart() {
            this.$Modal.confirm({
                title: "提示",
                content: "<p>确定要清空选品库吗？清空后不可恢复</p>",
                onOk: () => {
                    APICart.clearCart().then((res) => {
                        if (res.code == 1) {
                            this.$Message.success("清空选品库成功");
                            this.getCartList();
                        } else {
                            this.$Message.error(res.msg);
                        }
                    });
                },
            });
        },
        // 跳转支付页面
        pay() {
            if (!this.checkedNum) {
                /* this.$router.push({
                    path: "/pay",
                    query: {
                        way: "CART"
                    }
                }); */

                let goodsArr = [];
                this.skuList.forEach((goods) => {
                    if (goods.checked) {
                        goodsArr.push({ goods_sku_id: goods.id, num: goods.cartnum });
                    }
                });

                let params = { goods_sku_ids: goodsArr };
                let purchase = this.purchase;

                console.log('purchase', purchase)
                if (!purchase || !purchase.type) {
                    this.$Modal.confirm({
                        render: (h) => {
                            return h(Input, {
                                props: {
                                    size: "large",
                                    value: '',
                                    autofocus: true,
                                    placeholder: '输入选品名称',
                                },
                                on: {
                                    input: (e) => {
                                        this.purchaseVal = e;
                                    }
                                }
                            })
                        },

                        onOk: () => {
                            if (this.purchaseVal) {
                                this.$Message.error('请输入选品名称');
                                return false;
                            }

                            params['name'] = this.purchaseVal;
                            APICart.submitCartGoods(params).then((res) => {
                                if (res.code == 1) {
                                    this.$Message.success("提交成功");
                                    this.getCartList();
                                } else {
                                    this.$Message.error(res.msg);
                                }
                            });
                        },


                    })
                } else {
                    if (purchase.type == 'purchase') {
                        params['purchase_id'] = purchase.id;
                    } else if (purchase.type == 'tender') {
                        params['tender_id'] = purchase.id;
                    }

                    APICart.submitCartGoods(params).then((res) => {
                        if (res.code == 1) {
                            this.$Message.success("提交成功");
                            this.getCartList();
                        } else {
                            this.$Message.error(res.msg);
                        }
                    });
                }



            } else {
                this.$Message.warning("请至少选择一件商品");
            }
        },

        // 展示优惠券
        showCoupon(storeId, index) {
            this.couponAvailable = index;
        },

        // 设置购买数量
        changeNum(val, id, index) {
            if (val) {
                APICart.setCartGoodsNum({
                    goods_id: id,
                    num: val
                }).then((res) => {
                    if (res.code == 1) {
                        //this.getCartList();
                        this.skuList[index]['cartnum'] = val;
                        this.$forceUpdate();
                        this.dtoFlowPrice();
                    }
                });
            }
        },
        // 设置商品选中状态
        /* async changeChecked(status, type, id) {
            const check = status ? 1 : 0;
            if (type === "all") {
                // 全选
                await APICart.setCheckedAll({
                    checked: check
                });
            } else if (type === "shop") {
                // 选中店铺所有商品
                await APICart.setCheckedSeller({
                    checked: check,
                    storeId: id
                });
            } else {
                // 单个商品
                await APICart.setCheckedGoods({
                    checked: check,
                    skuId: id
                });
            }

            this.getCartList();
        }, */

        async changeChecked(status, type, id = null, index = null) {
            let check = status;
            let skuList = deepClone(this.skuList);
            if (type === "all") {
                let checkedNum = 0;
                for (let i in skuList) {
                    skuList[i].checked = check;
                    if (check) {
                        checkedNum++;
                    }
                }
                this.checkedNum = checkedNum;
                this.allChecked = check;
                this.skuList = skuList;
                this.dtoFlowPrice();
            } else if (type === "shop") {

            } else {
                skuList[index].checked = check;
                this.checkedNum = check ? this.checkedNum + 1 : this.checkedNum - 1
                if (this.checkedNum > skuList.length) {
                    this.allChecked = true;
                } else {
                    this.allChecked = false;
                }
                this.skuList = skuList;
                this.dtoFlowPrice();
            }
        },

        dtoFlowPrice() {
            let prices = 0;
            for (let i in this.skuList) {
                if (this.skuList[i].checked) {
                    prices += parseFloat(this.skuList[i].price * this.skuList[i].cartnum);
                }
            }
            this.priceDetailDTO.flowPrice = prices.toFixed(2);
        },

        // 领取优惠券
        async receiveShopCoupon(item) {
            let res = await APIMember.receiveCoupon(item.id);
            if (res.success) {
                this.$set(item, "disabled", true);
                this.$Message.success("领取成功");
            } else {
                this.$Message.error(res.msg);
            }
        },
        // 选品库列表
        async getCartList() {
            this.loading = true;
            try {
                let res = await APICart.cartGoodsAll();
                this.loading = false;
                if (res.code == 1) {
                    //this.cartList = res.data.items;
                    //this.priceDetailDTO = res.result.priceDetailDTO;

                    this.skuList = res.data.items;
                    this.checkedNum = 0;
                    let allChecked = true;
                    /* for (let k = 0; k < this.cartList.length; k++) {
                        let shop = this.cartList[k];
                        let list = await APIMember.couponList({
                            storeId: shop.storeId
                        });
                        shop.couponList.push(...list.result.records);
                    } */
                    for (let i = 0; i < this.skuList.length; i++) {
                        if (this.skuList[i].checked) {
                            this.checkedNum++;
                        } else {
                            this.skuList[i].checked = false;
                            allChecked = false;
                        }
                    }
                    this.$forceUpdate();
                    this.allChecked = allChecked;

                    this.goodsTotal = res.data.total;
                }
            } catch (error) {
                this.loading = false;
            }
        },
        // 
        cartH(){
         this.cartHeadth= document.documentElement.clientHeight
        }
    },
    mounted() {
        this.getCartList();
        this.cartH()
        /* APICart.cartCount().then((res) => {
          // 选品库商品数量
          if (res.success) this.goodsTotal = res.result;
        }); */
    },
};
</script>

<style scoped lang="scss">


/** logo 搜索 start **/
.logo {
    height: 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px auto 0;

    div:nth-child(1) {
        display: flex;
        justify-content: space-between;
        align-items: center;

        img {
            width: 150px;
            height: auto;
            cursor: pointer;
        }

        div:nth-child(2) {
            width: 200px;
            color: #999;
            font-size: 16px;
            margin: 0 20px;

            span {
                color: $theme_color;
            }
        }
    }
}

.cart-content {
    margin: 0 auto;
    width: 1200px;
    position: relative;
 
}

/** logo end */
/** step步骤条 */
.cart-steps {
    height: 30px;
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    span {
        @include content_color($light_content_color);
        height: 30px;
        text-align: center;
        line-height: 30px;
        display: inline-block;
        padding: 0 15px;
    }

    .ivu-icon {
        @include content_color($light_content_color);
        font-size: 20px;
        margin: 0 15px;
    }

    .active {
        border-radius: 50px;
        background-color: #ff8f23;
        color: #fff;
    }

    .active-arrow {
        color: #ff8f23;
    }
}

/** 步骤条和配送区域总体 */
.available-area {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
}

.cart-goods-title div {
    text-align: unset !important;
}

/** 商品列表 */
.cart-goods {
    &-title {
        height: 50px;
        @include background_color($light_white_background_color);
        @include title_color($title_color);
        display: flex;
        align-items: center;
        padding: 0 20px;

        div {
            text-align: center;
        }

        .goods-title {
            flex: 1;
        }
    }

    .cart-empty {
        width: 100%;
        text-align: center;
        height: 300px;
        padding-top: 100px;
    }

    &-items {
        .shop-name {
            height: 50px;
            display: flex;
            align-items: center;
            padding: 0 20px;
            position: relative;
            @include title_color($light_title_color);

            >* {
                width: 50%;
            }

            .go-shop-page:hover {
                color: $theme_color;
                cursor: pointer;
            }

            .customer-service {
                margin-left: 5px;
                color: #fcc217;
                cursor: pointer;

                &:hover {
                    color: $theme_color;
                }
            }

            /** 优惠券 */
            .shop-coupon {
                width: 80px;
                height: 24px;
                position: relative;
                // background: url(../assets/images/cart-coupon-icons02.png) 0 0 no-repeat;

                >div {
                    position: absolute;
                    top: 35px;
                    left: 0;
                    width: 300px;
                    height: 300px;
                    background-color: #fff;
                    border: 1px solid $theme_color;
                    // border-radius: 3px;
                    z-index: 1;
                    padding: 10px 20px;

                    &::before {
                        content: "";
                        display: block;
                        // background: url(../assets/images/cart-coupon-icons02.png) 0 -58px no-repeat;
                        width: 80px;
                        height: 12px;
                        position: absolute;
                        top: -12px;
                        left: 0;
                    }

                    .coupon-item {
                        margin-bottom: 10px;

                        span:nth-child(1) {
                            border: 1px solid #e33937;
                            display: inline-block;
                            padding: 3px 10px;
                            color: $theme_color;
                            border-radius: 3px;
                        }

                        span:nth-child(2) {
                            font-size: 12px;
                            margin-left: 5px;
                            color: #999;
                        }

                        .coupon-btn {
                            height: 26px;
                            float: right;
                            font-size: 12px;
                        }

                        &::after {
                            display: block;
                            content: "";
                            clear: right;
                        }
                    }
                }
            }

            .promotion-notice {
                text-align: right;
                font-size: 12px;
            }

            .shop-coupon-show {
                background-position-y: -34px;
            }
        }

        .goods-item {
            position: relative;
            @extend .cart-goods-title;
            @include background_color($light_white_background_color);
            padding: 10px 20px;
            height: auto;

            >div:nth-child(1) {
                padding-left: 15px;
                width: 30px;
            }

            >div:nth-child(2) {
                cursor: pointer;
                display: flex;
                box-sizing: border-box;
                //padding-left: 20px;
                position: relative;

                img {
                    width: 70px;
                    height: 70px;
                }

                >div>p {
                    @include content_color($light_content_color);
                    font-size: 13px;
                    text-align: left;
                    margin-left: 10px;

                    &:hover {
                        color: $theme_color;
                    }
                }
            }

            >div:nth-child(5) {
                font-weight: bold;
            }

            .num-input {
                width: 60px;
                border: 1px solid #999;
                border-radius: 5px;
                padding: 0 5px;

                &:focus {
                    outline-color: $theme_color;
                }
            }
        }

        .error-goods {
            position: absolute;
            width: 100%;
            height: 100%;
            margin-left: -20px;
            background-color: rgba($color: #999, $alpha: 0.5);
            z-index: 10;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-left: 150px;
            color: #000;
            padding-right: 30px;
        }
    }

    &-footer {
        @extend .cart-goods-title;
        position: sticky;
        bottom: 0;
        border-top: 1px solid #ddd;
        margin-top: 10px;
        padding: 0 0 0 20px;
        line-height: 50px;
        justify-content: space-between;

        >div {
            display: flex;
            text-align: center !important;
        }

        .selected-count {
            span {
                color: $theme_color;
            }
        }

        .save-price span {
            color: #000;
        }

        .total-price div {
            color: $theme_color;
            font-size: 20px;
        }

        .pay {
            background-color: $theme_color;
            width: 150px;
            font-size: 20px;
            color: #fff;
            height: 100%;
            line-height: 50px;
            cursor: pointer;
        }
    }

    .handle-btn {
        font-size: 12px;
        color: $handle-btn-color;
        cursor: pointer;

        &:hover {
            color: $theme_color;
        }
    }
}

.like {
    width: 1200px;
    margin: 10px auto;
    // padding: 20px 0;
    @include white_background_color();
}

.likeGoods,
.shop-nav-container {
    width: 1200px;
    margin: 0 auto;
}

.ivu-divider {
    background: $theme_color;
    height: 2px;
}

.width_150 {
    width: 150px;
}

.width_60 {
    width: 60px;
}

.promotion {
    display: flex;
    margin-top: 5px;
    margin-left: 5px;

    >span {
        border: 1px solid $theme_color;
        color: $theme_color;
        font-size: 12px;
        border-radius: 2px;
        padding: 0 2px;
    }

    >p {
        font-size: 12px;
        margin-left: 10px;
        color: #999;
    }
}

.cart-goods-footer>div {
    display: flex;
    align-items: center;
    overflow: hidden;
}

.total-price {
    display: flex;
    align-items: center;
}
</style>
<style>
.ivu-input-number-input {
    text-align: center;
}
</style>
